package com.jackrain.nea.omslocal.Dao;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.service.GetSqunceService;
import com.jackrain.nea.omslocal.service.LocalLogService;
import com.jackrain.nea.omslocal.service.SendMqServies;
import com.jackrain.nea.omslocal.util.JsonKeyCheck;
import com.jackrain.nea.omslocal.util.PackageJsonSqlUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;

/**
 * @Discription: 京东退单下载
 * Created with IntelliJ IDEA.
 * @Author wcy
 * @Date 2018/5/9 9:25:00
 */
@Slf4j
@Component
public class JingDongRefundDao {
    @Autowired
    private LocalLogService localLogService;

    @Autowired
    private GetSqunceService getSqunceService;

    @Autowired
    private PackageJsonSqlUtil packageJsonSqlUtil;

    @Autowired
    private SendMqServies sendMqServies;

    @Autowired
    private PropertiesConf pconf;

    public void refundStart(JSONArray tempArr, String msgkey, String topic,String tag) {
        JSONObject retObj = new JSONObject();
        JingDongRefundDao jingDongRefundDao = ApplicationContextHandle.getBean(JingDongRefundDao.class);
        String jdLogRetTopic = pconf.getProperty("ons.jdLogRetTopic","");
        System.out.println(tempArr.toJSONString());
        int countFaild = 0;
        StringBuffer tids = new StringBuffer();
        String sellerNick = null;
        //JSONArray tempArr = tempObj.getJSONArray("partReceiveDtoList");
        if (tempArr == null || tempArr.isEmpty()) {
            // 订单数据为空, 不需操作
            log.debug("京东订单数据为空, msgkey : " + msgkey);
            return;
        }
        for (Object obj : tempArr) {
            //服务单号
            Long afsServiceId = 0L;
            // 退单数据
            JSONObject refundObj = null;

            String orderStatus = null;
            try {


                // 循环遍历jsonarr, 插入数据
                refundObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                sellerNick = refundObj.getString("nick");
                orderStatus = refundObj.getString("afsServiceStatusName");
                JSONObject afsFreightOutObj = refundObj.getJSONObject("freightmessage");
                //refundObj.put("expressCode",((String[])afsFreightOutObj.get("expressCode"))[0]);
                //refundObj.put("expressCompany",((String[])afsFreightOutObj.get("expressCompany"))[0]);
                if (refundObj!=null&&afsFreightOutObj!=null){
                    for (String s : afsFreightOutObj.keySet()) {
                        if (!"afsServiceId".equals(s)){
                            refundObj.put(s,afsFreightOutObj.get(s));
                        }
                    }
                }
                System.out.println("线上接收消息体===>"+refundObj.toJSONString());
                afsServiceId = refundObj.getLong("afsServiceId");
                tids.append(",").append(afsServiceId);
                // 根据 平台 订单 id 查询数据库,判断该数据是 新增 或是 修改
                String selectSql = "SELECT id FROM T_OMS_JD_REFUND WHERE afsServiceId = ?";
                int id = Tools.getInt(QueryEngine.getInstance().doQueryOne(selectSql, new Object[]{afsServiceId}), -1);
                if (id < 0) {
                    // 数据不存在, 新增退单数据
                    System.out.println("传入的参数====="+refundObj.toJSONString());
                    jingDongRefundDao.saveJdRefund(refundObj);
                } else {
                    // 数据存在,根据查询的id 更新数据
                    jingDongRefundDao.updateJdRefund(refundObj,id);
                }
                localLogService.insertLogForJd(null,afsServiceId.toString(),topic,msgkey,sellerNick,orderStatus,0);
            } catch (Exception e) {
                // 发生异常,处理
                // 获取流
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                // 逐条将错误信息以消息发送到线上发送到线上
                JSONObject errObj = new JSONObject();
                errObj.put("flag",0);
                errObj.put("platid", afsServiceId);
                errObj.put("sellernick", sellerNick);
                errObj.put("topic", topic);
                errObj.put("tag", tag);
                errObj.put("msgkey", msgkey);
                // 线下消费报错的主机 ip
                errObj.put("ip", NetUtils.getLocalAddress());
                // 将错误以流写出
                e.printStackTrace(pw);
                errObj.put("errmsg", sw.toString());
                errObj.put("sendtime", System.currentTimeMillis());
                try {
                    sendMqServies.sendMqObj(errObj, pconf.getProperty("ons.jdLogErrTopic"), tag);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    log.debug("京东退单发送错误信息失败");
                }
                log.debug("京东退单插入失败 : tid :" + afsServiceId + "msgkey : " + msgkey + sw.toString());
                // 处理异常  1.将错误信息发送到线上  2. 将错误信息保存到本地数据库
                countFaild++;
                // 插入本地错误
                localLogService.insertLogForJd(e.getMessage(),afsServiceId.toString(),topic,msgkey,sellerNick,orderStatus,1);
            }

        }
        retObj.put("flag",0);
        retObj.put("tag",tag);
        retObj.put("sellernick",sellerNick);
        retObj.put("msgkey",msgkey);
        retObj.put("msgsize",tempArr.size());
        retObj.put("topic",topic);
        retObj.put("tids",tids.deleteCharAt(0).toString());
        retObj.put("successcount",tempArr.size()-countFaild);
        retObj.put("failedcount",countFaild);
        try {
            sendMqServies.sendMqRetLogObj(retObj,jdLogRetTopic,tag,sellerNick);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("京东退单发送回执信息失败");
        }
    }

    /**
     * 保存京东退单数据
     *
     * @param refundObj
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveJdRefund(JSONObject refundObj) throws ParseException {
        System.out.println("要插入的refundObj1111====="+refundObj.toJSONString());
        long id = 0L;
        if (refundObj!=null){
            String productTableName = "T_OMS_JD_REFUND";

            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson =  ApplicationContextHandle.getBean(JsonKeyCheck.class);
                refundObj = checkjson.checkJsonkey(refundObj, productTableName, checkjson.getInsertcolsmap());
            }
            refundObj.replace("afsApplyTime",new Date(refundObj.getLong("afsApplyTime")));
            refundObj.replace("afsApprovedTime",new Date(refundObj.getLong("afsApprovedTime")));
            // 获取退单表的 sequences , 添加 必须字段
            id = getSqunceService.getSqunce(productTableName);
            refundObj.put("id", id);
            System.out.println("要插入的refundObj222====="+refundObj.toJSONString());
            Object[] objArr = refundObj.values().toArray();
            // 拼接 sql
            String columnName = packageJsonSqlUtil.packageInsertCloumnName(refundObj);
            String columnValue = packageJsonSqlUtil.packageInsertColumnValue(objArr);

            String sql = "insert into T_OMS_JD_REFUND (" + columnName + ") values (" + columnValue + ")";
            log.debug("插入京东退单表 sql : " + sql);
            System.out.println("插入京东退单表 sql : " + sql);
            QueryEngine.getInstance().executeUpdate(sql, objArr);
            // 在执行完之后需要更改主表的 istrans 字段为 0

            String sql2 = "update T_OMS_JD_REFUND SET istrans = 0 WHERE id = ?";
            QueryEngine.getInstance().executeUpdate(sql2, new Object[]{id});
            System.out.println("插入退单表成功。。。。");
        }else {
            log.debug("退单数据为空 id " + id);
        }
    }

    /**
     * 修改商品主表数据
     *
     * @param refundObj
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJdRefund(JSONObject refundObj, long id) throws ParseException {
        if (refundObj!=null){
            String orderTableName = "T_OMS_JD_REFUND";
            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
                refundObj = checkjson.checkJsonkey(refundObj, orderTableName, checkjson.getUpdatecolsmap());
            }

            refundObj.replace("afsApplyTime",new Date(refundObj.getLong("afsApplyTime")));
            refundObj.replace("afsApprovedTime",new Date(refundObj.getLong("afsApprovedTime")));
            String params = packageJsonSqlUtil.packageUpdateCloumnName(refundObj);
            Object[] objArr =packageJsonSqlUtil.packageUpdateColumnValue(refundObj);

            String sql = "update T_OMS_JD_REFUND set " + params + " where id = ?";
            QueryEngine.getInstance().executeUpdate(sql, ArrayUtils.add(objArr, id));
            System.out.println("更新退单表完成。。。");
            String sql2 = "update T_OMS_JD_REFUND SET istrans = 0 WHERE id = ?";
            QueryEngine.getInstance().executeUpdate(sql2, new Object[]{id});
        }else {
            log.error("退单数据为空");
        }
    }

}
